/**
 * Project: springyounger.lottey.web
 * 
 * File Created at 2009-12-29
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;

import com.springyouner.lottery.framework.UserSession;
import com.springyouner.lottery.tools.Encrypt;
import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.User;
import com.springyounger.lottery.service.user.UserService;

/**
 * TODO Comment of SignonController
 * 
 * @author Administrator
 */
public class SignonController implements Controller {

	private UserService userService;

	private static final Logger logger = LoggerFactory
			.getLogger(SignonController.class);

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (null == request.getParameter("username")) {
			return new ModelAndView("index");
		}
		String username = LotteryUtil.trim(request.getParameter("username"));
		// md5转换
		String password = Encrypt.encodeMD5(request.getParameter("password"));
		User tempUser = new User();
		tempUser.setUsername(username);
		tempUser.setPassword(password);
		User user = userService.getUser(tempUser);
		if (null == user) {
			logger.info("用户不存在,{}", username);
			return new ModelAndView("errors", "message", "用户名或密码错误!");
		} else {
			UserSession userSession = new UserSession(user);
			request.getSession().setAttribute("userSession", userSession);
			String singonForward = request.getParameter("singonForward");
			if (null != singonForward) {
				response.sendRedirect(singonForward);
				return null;
			} else {
				// 根据权限转到不同的页面
				int privilege = Integer.parseInt(user.getRoleid());
				if (privilege == User.PRIVILEGE_ADMIN) {
					logger.info("跳转到管理页面 {}", username);
					return new ModelAndView(new RedirectView("admin/index.do"));
				} else {
					logger.info("跳转到用户页面  {}", username);
					return new ModelAndView("redirect:index.do");
				}
			}
		}
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
